<?php

namespace app\api\admin\v1\service\finder;

use zhanshop\server\Request;
use zhanshop\server\Response;

class CoroutineList extends BaseFinder
{
    protected $headToolbar = [];

    protected $rowToolbar = [
        [
            'event' => 'open',
            'ico' => '&#xe642;',
            'title' => '调用栈',
            'method' => 'trace',
            'field' => '',
            'page' => './page/main/coroutine-trace.html',
        ],
    ];

    protected function getCols(string $schma){
        $this->menuData['id'] = 'id';
        return [
            'id' => [
                'field' => 'id',
                'title' => '协程ID',
                'type' => 'text',
                'width' => 180,
            ],
            'runtime' => array (
                'field' => 'runtime',
                'title' => '运行时长',
                'type' => 'text',
                'width' => 180,
            ),
            'memory' => array (
                'field' => 'memory',
                'title' => '内存占用',
                'type' => 'int',
                'input_type' => 'text',
                'width' => 120,
            )
        ];
    }

    protected function data(int $page, int $limit, array $order, array $search){
        $list = [];
        $number = 0;
        foreach(\Swoole\Coroutine::list() as $cid){
            if($number >= 2000){
                break;
            }
            $list[] = [
                'id' => $cid,
                'runtime' => (\Swoole\Coroutine::getElapsed($cid) / 1000).'秒',
                'memory' => round((\Swoole\Coroutine::getStackUsage($cid) / 1024 / 1024), 2).'MB',
            ];
            $number++;
        }
        return [
            'total' => $number,
            'list' => $list
        ];
    }

    public function trace(Request $request, Response $response)
    {
        $id = $request->param('id');
        $trace = \Swoole\Coroutine::getBackTrace($id);
        return [
            'body' => $trace
        ];
    }
}